package fi.jamk.ourcookingapp.activity;

import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONException;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import fi.jamk.ourcookingapp.R;
import fi.jamk.ourcookingapp.adapter.MyReceiptAdapter;
import fi.jamk.ourcookingapp.backend.architecture.manager.ReceiptManager;
import fi.jamk.ourcookingapp.backend.exceptions.EmptySearchException;
import fi.jamk.ourcookingapp.backend.exceptions.NoReceiptException;
import fi.jamk.ourcookingapp.backend.model.Receipt;

/**
 * This activity is for showing the favourite receipts of the current user
 * @author Marius
 */
public class FavouritesActivity extends ListActivity implements OnScrollListener  {

	private int count;
	private int limitCount;
	
	private List<Receipt> filter;
	private MyReceiptAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// when an item is clicked get the receipt and start detail activity
		Receipt rec = (Receipt)getListAdapter().getItem(position);
		Intent detailIntent = new Intent(this, ReceiptDetailActivity.class);
		detailIntent.putExtra(ReceiptDetailActivity.ARG_ITEM, rec);
		detailIntent.putExtra(ReceiptDetailActivity.SOURCE, ReceiptDetailActivity.FAVOURITES);
		startActivity(detailIntent);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		try {
			// setting adapter for the favourites
			AppActivity.facade.setFilter(ReceiptManager.LIMIT_KEY, 0);
			filter = AppActivity.facade.getFavourites();
			adapter = new MyReceiptAdapter(this, R.layout.receipt_list_item, filter);
			setListAdapter(adapter);
			count = 1;
			limitCount = 0;
		} catch (JSONException | InterruptedException | ExecutionException | EmptySearchException e) {
			e.printStackTrace();
		}
		getListView().setOnScrollListener(this);
	}
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if(firstVisibleItem == count){
			try {
				limitCount++;
				AppActivity.facade.setFilter(ReceiptManager.LIMIT_KEY, ReceiptManager.LIMIT * limitCount);
				for (Receipt rec : AppActivity.facade.filter(false)) {
					this.filter.add(rec);
				}
				adapter.notifyDataSetChanged();
				count += 7;
			} catch (EmptySearchException | NoReceiptException | InterruptedException | ExecutionException | JSONException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}

}
